﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime.Host;

namespace Host
{
    public class Program
    {
        static void Main(string[] args)
        {
            AppDomain hostDomain = AppDomain.CreateDomain("OrleansHost", null, new AppDomainSetup
            {
                AppDomainInitializer = InitSilo,
                AppDomainInitializerArguments = args,
            });

            Console.WriteLine("Orleans Silo is running.\nPress Enter to terminate...");
            while (true)
            {
                Thread.Sleep(1000 * 60);
                XServer.Config.ConfigMetaData.LoadAllConfig();
            }

            hostDomain.DoCallBack(ShutdownSilo);
        }

        static void InitSilo(string[] args)
        {
            siloHost = new SiloHost(System.Net.Dns.GetHostName());
            siloHost.ConfigFileName = "OrleansConfiguration.xml";
            siloHost.InitializeOrleansSilo();
            var started = siloHost.StartOrleansSilo();
            if (!started)
            {
                Console.Error.WriteLine("Failed to initialize Orleans silo");
            }

            XServer.SDK.Profile.Enbale = HostSettings.EnableProfile;
            XServer.SDK.LoggerProvider.InitLogger(HostSettings.LogPrefix, HostSettings.LogLevel);
            XServer.Config.ConfigMetaData.InitConfigPath(HostSettings.ConfigPath);
            XServer.Config.ConfigMetaData.LoadAllConfig();
            if (!String.IsNullOrWhiteSpace(HostSettings.MysqlPassword))
                XServer.Record.MysqlUtils.Password = HostSettings.MysqlPassword;
            if (!String.IsNullOrWhiteSpace(HostSettings.MysqlUser))
                XServer.Record.MysqlUtils.UserName = HostSettings.MysqlUser;
            XServer.Record.MysqlUtils.DBIpAddr = HostSettings.MysqlIp;
            XServer.Record.MysqlUtils.DBName = HostSettings.MysqlDB;
            using (var conn = XServer.Record.MysqlUtils.GetConn())
            {
            }
        }

        static void ShutdownSilo()
        {
            if (siloHost != null)
            {
                siloHost.Dispose();
                GC.SuppressFinalize(siloHost);
                siloHost = null;
            }
        }

        static SiloHost siloHost;
    }
}